# -*- coding=utf-8 -*-

import shlex, subprocess, sys, os
import socket
import win32net, win32file
import string
from threading import Thread, Lock
import time
import id3

# 要排除的东西
filter_word = (\
		'MKZ', 'mkz', '九州', '斗神', 'client', 'Client', 'M.K.Z', '天地', '三国杀', '大航海', '素材', '客户端', '天骄', '楚汉', '音效资料', 'newsound', 'NewSound', 
		'视频提交', 'work', '目标产品', 'FRAPS 录像', 'rtx', '调整好的音乐', 'JiuZhou', 'Jiuzhou', '暇月战歌', )

# 文件名
names = ('audio', '评书', '说说', '相声', 'game', 'video', 'tutorial', )

# 有效扩展名
avail_ext = {	'audio' : ('mp3', 'ogg', 'flac', 'ape', 'wma', ),
				'video' : ('rmvb', 'avi', 'wmv', 'mkv', 'mp4', 'flv', ),
			}

avail_tutorial = ( '游戏资 料', '资源添加视频', '教程', '教学', '技术相关', '游戏宣传视频参考', 'After Effects', '参考资料', 'AE5', 'fume fx', 'ZBrush', 'UDK', '美术参考', '动作参考', 'AE6', )

avail_speak = ( '小说', '史上第一混乱', '史记', '36计', '了凡四训',
				'史上第一妖', '诸子百家', '蒙面之城', '三国演义', '乱世枭雄', 
				'七夜谈', '十岁前，决定孩子的一生', '佛', '幸福人生', '有声读物', '盗墓',
				'秦始皇', '老罗', '史上第一混搭', '史说', '鬼吹灯', '正史', '听的', )
avail_ps = ( '评书', '单田芳', '国学堂', '袁腾飞', )
avail_xs = ( '相声', '德纲', '德刚', '何云伟', '李菁', '曹云金', '刘艺', '于谦', '赵云侠', '李云杰', '侯震', '王玥波', )

avail_game = ( '音乐参考', '鬼童', '音效资源', '游戏', 'dota', 'GAMES', '层级建筑视频', '男战士', 'wowmusic', )

# 分类
name_category = { '评书':avail_ps, '说说':avail_speak, 'game': avail_game, 'tutorial' : avail_tutorial, '相声':avail_xs, }

class StdOut:
	def write( self, str ):
		print '--', str

	def fileno(self):
		return 0

output_lock = Lock()
share_lock  = Lock()
audio_files = []
video_files = []

file_dict = {}
for name in names :
	filename = '%s_record.m3u' % (name.decode('utf-8'))
	f = open( filename, 'wb' )
	f.write('%c%c%c'%(0xEF, 0xBB, 0xBF))
	file_dict[name] = {'file':f, }

# audio_record = open('audio_record.log', 'wb')
# video_record = open('video_record.log', 'wb')
# 
# for f in [audio_record, video_record, ]:
# 	f.write('%c%c%c'%(0xEF, 0xBB, 0xBF))
def write_m3u( f, uri ):
	output_lock.acquire()
	f.write( '%s\n' %(uri.encode('utf-8') ) )
	f.flush()
	output_lock.release()

def find_path( cur_path, depth, sub_path, **func ):
	try:
		if type(cur_path) != type(u' '):
			print type(cur_path)
			exit(1)
		if not os.path.isdir( cur_path ) :
			return

		# 屏蔽关键词
		for word in filter_word :
			if -1 != cur_path.find(word.decode('utf-8')) :
				return

		cur_list = os.listdir( cur_path )
		for item in cur_list:
			full_path = '%s\\%s' % (cur_path, item)
			if os.path.isdir( full_path ) :
				if depth-1 > 0 :
					sub_path.append( [full_path, depth-1] )
			elif os.path.isfile( full_path ):
				ignore = False
				for word in filter_word :
					if -1 != item.find(word.decode('utf-8')) :
						ignore = True
						break
				if ignore :
					continue

				# print type(full_path), full_path
				ext_name = item.split('.')[-1]
				ext_name = string.lower(ext_name)
				for k, v in avail_ext.items() :
					if ext_name in v :
						ignore = False
						# 依据文件名详细分类
						for class_k, class_v in name_category.items() :
							if ignore :
								break
							for focus in class_v :
								if -1 != full_path.find( focus.decode('utf-8') ):
									f = file_dict[class_k]['file']
									write_m3u( f, full_path )
									ignore = True
									break

						if not ignore :
							f = file_dict[k]['file']
							write_m3u( f, full_path )

	except WindowsError, e:
		pass
	# except UnicodeEncodeError, e:
	# 	pass

class SearchThread( Thread ):
	def __init__( self, group=None, target=None, name=None, *args, **kwargs ) :
		Thread.__init__( self, group, target, name, args, kwargs )
		self.search_path = kwargs['root']

	def run(self):
		while len(self.search_path) > 0 :
			p, l = self.search_path[0]
			find_path( p, l, self.search_path )
			del self.search_path[0]

def CreateSearchThread( share_name ):
	search_path = [[share_name,3], ]
	t = SearchThread( root=search_path )
	t.start()
	return t

def AssignSearchThread( tasks, thread_poll, max_thread ):
	# print 'Tasks = ', tasks, '\nthreads = ', thread_poll
	while len(thread_poll) < max_thread and len(tasks) > 0 :
		t = CreateSearchThread( tasks[0] )
		thread_poll.append( t )
		del tasks[0]

def WatchThread( thread_poll ):
	i = 0
	while i < len(thread_poll):
		if thread_poll[i].isAlive() == False:
			del thread_poll[i]
		else:
			i += 1


out_buf = StdOut()
command_line = 'net view'
args = shlex.split(command_line)
p = subprocess.Popen( args, stdout=subprocess.PIPE )
# output = p.stdout.readline()
# sys.stdout.write(output)
# p.wait()
lines = p.stdout.readlines()
max_search_thread = 50 * 2
all_thread = []
all_share  = []
for line in lines:
	if line[0] == '\\':
		end = line.find(' ')
		name = line[2:end]
		try:
			info = socket.gethostbyname(name)
			root_path = '\\\\'+info
			print '%-16s %s' % (info, name)
			try:
				# cur_list = os.listdir(root_path)
				data, total, resume = win32net.NetShareEnum(name, 0)
			except:
				pass
			else:
				# print '%-16s %s' % (info, name)
				for share in data:
					# print '%s%s'% (' '*4, share['netname'])
					WatchThread( all_thread )
					cur_path = root_path + '\\' + share['netname']
					all_share.append( cur_path )
					AssignSearchThread( all_share, all_thread, max_search_thread )
		except socket.gaierror, e:
			pass

share_lock.acquire()
share_lock.release()

wait = True
while wait :
	time.sleep( 1.0 )
	WatchThread( all_thread )
	AssignSearchThread( all_share, all_thread, max_search_thread )
	wait = len(all_thread) > 0

for name, value in file_dict.items() :
	f = value['file']
	f.flush()
	f.close()

print 'The End.'

